package com.geek.factory.service;

import com.geek.factory.constant.MessageConstant;
import com.geek.factory.constant.RedisConstant;
import com.geek.factory.entity.User;
import com.geek.factory.mapper.UserMapper;
import com.geek.factory.result.Result;
import com.geek.factory.result.ResultEntityEnum;
import com.geek.factory.utils.JwtUtil;
import com.geek.factory.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/6/26
 */
@Service
public class SmsService {

    //RedisTemplate<String,String>
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;

    public Result sendMsgByLogin(String phone) {
        //1.接收手机号码，查询一分钟有效的验证码是否存在，若存在则直接返回
        if (redisTemplate.opsForValue().get(phone + MessageConstant.LOGIN_SMS) != null) {
            return new Result(false, "一分钟内不允许重复发送验证码，获取验证码失败！", null);
        }

        //2.生成4位、6位随机验证码
        String code = RandomUtil.getSixBitRandom();

        //TODO 阿里云SMS短信服务

        //4.在Redis中，存储一分钟有效的验证码 key phone_001
        //在Redis中，存储五分钟有效的验证码   key phone_001_param
        redisTemplate.opsForValue().set(phone + MessageConstant.LOGIN_SMS, code, 1, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(phone + MessageConstant.LOGIN_SMS + "_" + code, code, 5, TimeUnit.MINUTES);
        return new Result(true, "验证码发送成功！", null);
    }

    //    public boolean checkCode(String phone, String code) {
//        // 这里假设你用 Redis 存储验证码
//        String realCode = redisTemplate.opsForValue().get("LOGIN_CODE:" + phone);
//        return code != null && code.equals(realCode);
//    }
    public boolean checkCode(String phone, String code) {
        String realCode = redisTemplate.opsForValue().get(phone + MessageConstant.LOGIN_SMS);
        return code != null && code.equals(realCode);
    }

    public String loginByPhone(String phone) {
        // 1. 查询用户
        User user = userMapper.selectByPhone(phone);
        if (user == null) return null;
        // 2. 生成token（可用JWT或自定义）
        String token = jwtUtil.createToken(user.getId().longValue(), user.getPhone());
        return token;
    }
}
